package com.yang.spingboot.yixincallback.web;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.yang.spingboot.yixincallback.util.AesUtils;
import com.yang.spingboot.yixincallback.util.MD5Utils;
import com.yang.spingboot.yixincallback.util.RsaUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * @author yanwei.yang
 * @date 2021/12/30 11:23
 * @description:
 */
@Controller
@RequestMapping("index")
public class IndexController {


    public static void main(String[] args) throws Exception {
        String aesKey = "EjaklqBcTCcsUDWC";  //固定一个或者每次随机生成一个
        String publicKey = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAIbwcoKbCSvmWTNaZl+OKqaYmzGGbfNgYUVvsuQ8etN3C9XLsXCIV8SErEswkyRRH6QkLSg5czIak8zcxw2ZNZ0CAwEAAQ==";
        String md5 = "TrSfmoXjlUZYlBRqLuPRfpHBHQJGQWzy";
        String aesKey2 = RsaUtils.encrypt(aesKey, publicKey);  //加密后的，放在header里
        Map<String, String> params = new HashMap<>();
        params.put("coName", "商户名称");
        params.put("date", "2021-12-30 11:00:00");
        params.put("order", "12345");
        params.put("shopCode", "123456");
        String json = JSONObject.toJSONString(params);// JSONUtils.toJSONString(params);
        byte[] jsonAes = AesUtils.aesEncryptToBytes(json, aesKey);
        String jsonAesHex = AesUtils.parseByte2HexStr(jsonAes);

        //md5摘要
        String sign = MD5Utils.MD5(jsonAesHex + md5);
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("hex", jsonAesHex);
        jsonObject.addProperty("sign", sign);
        jsonObject.addProperty("time", System.currentTimeMillis());

        String requestUrl = "https://www.goodly.com.cn/crediteaseApi/wechat/autohome/callback";
        URL url = new URL(requestUrl);
        HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
        httpUrlConn.setDoOutput(true);
        httpUrlConn.setDoInput(true);
        httpUrlConn.setUseCaches(false);
        httpUrlConn.setRequestProperty("Content-type", "application/json");
        httpUrlConn.setRequestProperty("aesKey", aesKey2);

        // 设置请求方式（GET/POST）
        httpUrlConn.setRequestMethod("POST");
        OutputStream outputStream = httpUrlConn.getOutputStream();
        // 注意编码格式，防止中文乱码
        outputStream.write(jsonObject.toString().getBytes("UTF-8"));
        outputStream.close();

        InputStream inputStream = httpUrlConn.getInputStream();
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

        StringBuffer buffer = new StringBuffer();
        String str = null;
        while ((str = bufferedReader.readLine()) != null) {
            buffer.append(str);
        }
        bufferedReader.close();
        inputStreamReader.close();
        // 释放资源
        inputStream.close();
        httpUrlConn.disconnect();
        String returnString = buffer.toString();

        //转json的工具类很多，可自选
        JsonObject jsonObject1 = new JsonParser().parse(returnString).getAsJsonObject();
        String hex = jsonObject1.get("hex").getAsString();

        //检验md5摘要，非必须
        String sign1 = jsonObject1.get("sign").getAsString();
        String sign2 = MD5Utils.MD5(hex + md5);
        if (!sign1.equals(sign2)) {
            //校验失败
            return;
        }


        //解密
        byte[] bytes = AesUtils.parseHexStr2Byte(hex);
        String aesString = AesUtils.aesDecryptByBytes(bytes, aesKey);
        System.out.println(aesString);

        //返回例子：{"success":false,"message":"订单不存在！","code":500,"result":null,"timestamp":1640776950222}
        //{"success":true,"message":"成功","code":0,"result":null,"timestamp":1640776950222}

    }
}
